package com.itheima.websocket.ws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.websocket.config.GetHttpSessionConfig;
import com.itheima.websocket.ws.pojo.ChatMessage;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat", configurator = GetHttpSessionConfig.class)
@Component
public class ChatEndpoint {

    private static final Map<String, Session> onlineUsers = new ConcurrentHashMap<>();

    // 不使用session时可以用springSecurity中获取并存在这里
    private HttpSession httpSession;

    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig)
    {
        // 1保存session
        this.httpSession = (HttpSession)endpointConfig.getUserProperties().get(HttpSession.class.getName());
        String user = (String) this.httpSession.getAttribute("user");
        onlineUsers.put(user,session);
        // 2广播有人登录了
        System.out.println("连接成功");
    }
    @OnMessage
    public void onMessage(String message)
    {
        // 将消息发给用户
        ChatMessage chatMessage = JSONObject.parseObject(message, ChatMessage.class);
        onlineUsers.forEach((username,session)->{
            try {
                session.getBasicRemote().sendText(chatMessage.getContent());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println(message);
    }
    @OnClose
    public void onClose()
    {
        // 1从onlineUsers中剔除
        String user = (String) this.httpSession.getAttribute("user");
        onlineUsers.remove(user);
        // 2通知其他用户
        System.out.println("连接关闭");
    }
}
